const api = require("../../utils/request.js");
const userApi = require("../../api/user.js");
const dateUtils = require("../../utils/date.js");
const asyncTools = require("../../utils/asyncTools.js");
Component({
  properties: {
    type: { type: String, value: "my" }, //list圈子，my自己主页动态，other别人主页动态，like，喜欢那边的动态
    userId: { type: String, value: "" },
  },
  data: {
    avatarUrl: "",
    unReadMessageCount: 0,
    hidden: true,
    loadingData: false, //数据是否正在加载中，避免数据多次加载
    pageNum: 1,
    pageSize: 50,
    curNum: 0, //上滑时接口返回数据数量，若小于pageSize责代码没有数据了
    communityList: [],
  },
  observers: {
    type: function (val) {
      if (val === "my") {
        this.getUnReadMessageCount();
      }
    },
  },
  lifetimes: {
    async created() {
      await this.loopWait(); //等待登录接口拿到数据
      this.getCommunityList();
    },
  },
  methods: {
    async getCommunityList() {
      let timeStampFlag = 0 //第一次查询的是0
      let len = this.data.communityList.length
      if (len > 0) {
        timeStampFlag = this.data.communityList[len - 1].timeStampFlag
      }
      //这边为了防止丢数据(同一时间点N多人同时发)/查重复数据(刷新前有人发了新动态)，用timeStampFlag字段对动态进行排序，后端会对统一毫秒发的动态再加1毫秒，保证没有在同一时间有不同的人发动态
      let info = {
        pageSize: this.data.pageSize,
        pageNum: this.data.pageNum,
        timeStampFlag
      };
      if (this.data.type !== "list") {
        info.userId = this.data.userId;
      }
      let res = await userApi.getListPublish(info);
      let data = [];
      if (res && res.data) {
        res.data.forEach((el) => {
          el.publishContent = JSON.parse(el.publishContent);
          el.publishContent.map((item) => {
            item.mode = "scaleToFill";
          });
          el.publishContent = el.publishContent.slice(0, 2); //文章展示前两个
          el.publishTime = dateUtils.timestampToTime(el.timeStampFlag, 1);
          data.push(el);
        });
        this.setData({ communityList: data, curNum: data.length });
        this.triggerEvent("getCommunityNum", {
          communityList: data.length,
          unReadMessageCount: this.data.unReadMessageCount,
        });
      }
    },
    //循环
    loopWait() {
      return new Promise(async (resolve) => {
        let delay = 100;
        while (delay > 0) {
          await asyncTools.delay(delay);
          if (getApp().globalData.isLogin === true) {
            delay = 0;
          }
        }
        resolve();
      });
    },
    async getUnReadMessageCount() {
      let res = await userApi.getUnReadMessageCount({
        userId: wx.getStorageSync("loginInfo").userId,
      });
      this.setData({
        unReadMessageCount: res.data.count,
        avatarUrl: res.data.avatarUrl,
      });
      this.triggerEvent("getCommunityNum", {
        communityList: this.data.communityList.length,
        unReadMessageCount: res.data.count,
      });
    },
    messageClick(e) {
      wx.navigateTo({
        url: `/pages/home/message/index?id=${this.data.userId}`,
      });
    },
    oneImageLoad(e) {
      let factor1 = (getApp().globalData.screenWidth - 68) / 344;
      let factor2 = e.detail.width / e.detail.height;
      let mode = factor2 > factor1 ? "widthFix" : "heightFix";
      let communityList = [];
      this.data.communityList.forEach((el) => {
        let publishContent = [];
        el.publishContent.forEach((item) => {
          if (item.type.indexOf("img") !== -1) {
            let idx = item.content.findIndex(
              (val) => val === e.currentTarget.dataset.src[0]
            );
            if (idx !== -1) {
              item.mode = mode;
            }
          }
          publishContent.push(item);
        });
        el.publishContent = publishContent;
        communityList.push(el);
      });
      this.setData({ communityList });
    },
    articleClick(e) {
      wx.navigateTo({
        url: `/pages/community/detail/index?articleId=${e.currentTarget.dataset.item.id}`,
      });
    },
    // 删除动态
    deleteClick(e) {
      let id = e.currentTarget.dataset.item.id;
      let _this = this;
      wx.showModal({
        title: "",
        content: "删除该动态？",
        success: function (res) {
          if (res.confirm) {
            _this.deleteItem(id);
          } else if (res.cancel) {
          }
        },
      });
    },
    async deleteItem(id) {
      let res = await userApi.deletePublish({ publishId: id });
      if (res.code == 200) {
        wx.showToast({ title: "删除成功", icon: "success", duration: 200 });
        //得删除数组不能重新请求接口
        let communityList = this.data.communityList.filter(
          (item) => item.id !== id
        );
        this.setData({ communityList });
      }
    },
    async profileClick(e) {
      // 判断是点击自己的图像 还是点击别人的图像
      let userId = wx.getStorageSync("loginInfo").userId;
      let url =
        e.currentTarget.dataset.item.userId === userId
          ? "/pages/home/index"
          : "/pages/home/otherProfile/index";
      wx[
        e.currentTarget.dataset.item.userId === userId
          ? "switchTab"
          : "navigateTo"
      ]({
        url: `${url}?userId=${e.currentTarget.dataset.item.userId}&nickName=${e.currentTarget.dataset.item.nickName}`,
      });
    },
    previewImage(e) {
      let list = e.currentTarget.dataset.src;
      wx.previewImage({
        current: list[0], // 当前显示图片的链接/路径
        urls: list[1], // 需要预览的图片链接/路径列表
      });
    },
    async subscribeClick(e) {
      let userInfo = wx.getStorageSync("userInfo");
      let item = e.currentTarget.dataset.item;
      if (userInfo.avatarUrl && userInfo.nickName) {
        let data = { followUserId: item.userId };
        let url =
          item.displayFollow === "2"
            ? "/wxUser/cancelFollow"
            : "/wxUser/addFollow";
        await api.request({ url, data, method: "post" });
        let communityList = [];
        this.data.communityList.map((val) => {
          if (val.userId === item.userId) {
            val.displayFollow = item.displayFollow === "2" ? "1" : "2";
          }
          communityList.push(val);
        });
        this.setData({ communityList });
      } else {
        getApp().globalData.jump = true;
        wx.switchTab({ url: `/pages/user/index` });
      }
    },
    async pullDownRefresh() {
      this.setData({ hidden: false, communityList: [], pageNum: 1 });
      await asyncTools.delay(500); //现在接口太快了，假装loading了一会
      if (!this.data.loadingData) {
        wx.showNavigationBarLoading();
        if(this.data.type === 'my') {
          this.getUnReadMessageCount();
        }
        await this.getCommunityList();
        this.setData({ loadingData: false, hidden: true });
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
      }
    },
    async reachBottom() {
      if (!(this.data.curNum < this.data.pageSize)) {
        let res = await userApi.getListPublish({
          pageSize: this.data.pageSize,
          pageNum:
            this.data.pageNum + (this.data.communityList.length === 0 ? 0 : 1),
          timeStampFlag:
            this.data.communityList.length === 0
              ? 0
              : this.data.communityList[this.data.communityList.length - 1]
                .timeStampFlag,
        });
        let data = [];
        if (res && res.data) {
          res.data.forEach((el) => {
            el.publishContent = JSON.parse(el.publishContent);
            el.publishContent = el.publishContent.slice(0, 2);
            el.publishTime = dateUtils.timestampToTime(el.timeStampFlag, 1);
            data.push(el);
          });
          let communityList = this.data.communityList.concat(data);
          this.setData({
            pageNum: this.data.pageNum + 1,
            communityList,
            curNum: data.length,
          });
          if (data.length === 0) {
            wx.showToast({
              title: "已经到底啦",
              icon: "success",
              duration: 2000,
            });
          }
        }
      } else {
        wx.showToast({ title: "已经到底啦", icon: "success", duration: 2000 });
      }
    },
  },
});
